{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "import email_read_util"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Download 2007 TREC Public Spam Corpus\n",
    "1. Read the \"Agreement for use\"\n",
    "   https://plg.uwaterloo.ca/~gvcormac/treccorpus07/\n",
    "\n",
    "2. Download 255 MB Corpus (trec07p.tgz) and untar into the 'chapter1/datasets' directory\n",
    "\n",
    "3. Check that the below paths for 'DATA_DIR' and 'LABELS_FILE' exist"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "DATA_DIR = 'datasets/trec07p/data/'\n",
    "LABELS_FILE = 'datasets/trec07p/full/index'\n",
    "TRAINING_SET_RATIO = 0.7"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "labels = {}\n",
    "# Read the labels\n",
    "with open(LABELS_FILE) as f:\n",
    "    for line in f:\n",
    "        line = line.strip()\n",
    "        label, key = line.split()\n",
    "        labels[key.split('/')[-1]] = 1 if label.lower() == 'ham' else 0"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "def read_email_files():\n",
    "    X = []\n",
    "    y = [] \n",
    "    for i in range(len(labels)):\n",
    "        filename = 'inmail.' + str(i+1)\n",
    "        email_str = email_read_util.extract_email_text(\n",
    "            os.path.join(DATA_DIR, filename))\n",
    "        X.append(email_str)\n",
    "        y.append(labels[filename])\n",
    "    return X, y"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "X, y = read_email_files()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/usr/local/lib/python3.6/site-packages/sklearn/model_selection/_split.py:2026: FutureWarning: From version 0.21, test_size will always complement train_size unless both are specified.\n",
      "  FutureWarning)\n"
     ]
    }
   ],
   "source": [
    "from sklearn.model_selection import train_test_split \n",
    "\n",
    "X_train, X_test, y_train, y_test, idx_train, idx_test = \\\n",
    "    train_test_split(X, y, range(len(y)), \n",
    "    train_size=TRAINING_SET_RATIO, random_state=2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.feature_extraction.text import CountVectorizer\n",
    "\n",
    "vectorizer = CountVectorizer()\n",
    "X_train_vector = vectorizer.fit_transform(X_train)\n",
    "X_test_vector = vectorizer.transform(X_test)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "             precision    recall  f1-score   support\n",
      "\n",
      "       Spam       0.99      0.94      0.97     15035\n",
      "        Ham       0.90      0.98      0.94      7591\n",
      "\n",
      "avg / total       0.96      0.96      0.96     22626\n",
      "\n",
      "Classification accuracy 95.6%\n"
     ]
    }
   ],
   "source": [
    "from sklearn.naive_bayes import MultinomialNB\n",
    "from sklearn.metrics import accuracy_score\n",
    "from sklearn.metrics import classification_report\n",
    "\n",
    "# Initialize the classifier and make label predictions\n",
    "mnb = MultinomialNB()\n",
    "mnb.fit(X_train_vector, y_train)\n",
    "y_pred = mnb.predict(X_test_vector)\n",
    "\n",
    "# Print results\n",
    "print(classification_report(y_test, y_pred, target_names=['Spam', 'Ham']))\n",
    "print('Classification accuracy {:.1%}'.format(accuracy_score(y_test, y_pred)))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
